package com.easytouch.core;

import android.os.SystemClock;

import com.easytouch.core.encryption.MD5;
import com.easytouch.core.model.GoodsDownloadModel;
import com.easytouch.core.model.GoodsModel;
import com.easytouch.core.utils.DownloadGoodsDatabaseUtils;
import com.easytouch.core.utils.FileTools;
import com.easytouch.core.utils.Log;
import com.easytouch.core.utils.SystemTools;
import com.easytouch.core.utils.Tools;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import static com.easytouch.core.Configure.DIRECTORY_CONFIG;

public class DownloadGoodsDatabaseThread extends Thread {

    private static String HTTP_HOST = "http://test.easytouch-manager.com:7008";
    private static final String INTERFACE_FIND_BARCODE = "/Interface/goods/findBarcode.do";
    private static final String INTERFACE_FIND_BARCODE_RE = "/Interface/goods/findBarcodeRe.do";

    private static final String APPID = "1e8d1b3ebb843511d36372c257dca0ebcf73e544";
    private static final String KEY = "xiaoyanzichuanhuayibeizheshubaoshangxuequyanzishuowoaini";
    private String mContentType = "application/x-www-form-urlencoded"; //"text/html  application/x-www-form-urlencoded  application/json  multipart/form-data;
    private String mCharset = "UTF-8";

    private static final int FAIL_ID_XML = 0;
    private static final int FAIL_ID_DOWNLOAD = 1;
    private static final int FAIL_ID_UNZIP = 2;
    private static final int FAIL_ID_COPY = 3;

    public static final String TYPE_PART = "01"; //部分更新
    public static final String TYPE_ALL = "02"; //全部更新
    public static final String TYPE_GOODS = "03"; //单独下载一个商品信息
    private String mType = TYPE_PART;

    private static volatile boolean isProcess = false; //当前是否在运行中
    private static volatile boolean isIdle = true; //是否空闲
    private static boolean isFirstLoopDeleteAllGoods = true;

    private Log mLogger = new Log("DownloadGoodsDatabaseThread.txt");

    private ArrayList<GoodsDownloadModel> mGoodsDownloadList = new ArrayList<>();
    private String mTaskId;

    private LinkedList<DownloadTaskModel> mTaskQueue = new LinkedList<>(); // 任务队列

    private String mBarcode;

    private int retryCount = 0;


    //以下三个方法实现了单例模式，同时保证懒加载和线程安全
    private static class Holder {
        private static DownloadGoodsDatabaseThread INSTANCE = new DownloadGoodsDatabaseThread();
    }

    public static DownloadGoodsDatabaseThread getInstance() {
        if (Holder.INSTANCE == null || Holder.INSTANCE.getState() == State.TERMINATED) {
            Holder.INSTANCE = new DownloadGoodsDatabaseThread();
        }
        return Holder.INSTANCE;
    }

    private DownloadGoodsDatabaseThread() {
    }

//    public static boolean isProcess()
//    {
//        return isProcess;
//    }

    public static boolean isIdle() {
        return isIdle;
    }

    public static void stopThread() {
        isProcess = false;
    }

    private synchronized void appendTaskQueueData(DownloadTaskModel data) {
        if (!mTaskQueue.contains(data)) {
            mTaskQueue.offer(data);
            mLogger.i("add task:" + data + ",count:" + mTaskQueue.size());
        }
    }

    private synchronized DownloadTaskModel getTaskQueueData() {
        return mTaskQueue.poll();
    }

    private synchronized int getTaskQueueCount() {
        return mTaskQueue.size();
    }

    public void startDownload(final String pType) {
//        mType = pType;
//        if(isProcess)
//        {
//            return;
//        }
        isFirstLoopDeleteAllGoods=true;
        appendTaskQueueData(new DownloadTaskModel(pType, ""));
        mLogger.i("current state:" + getState());
        if (getState() == State.NEW) {
            start();
        }
    }

    public void startDownloadGoods(final String pBarcode, final int pFrom) {
        appendTaskQueueData(new DownloadTaskModel(TYPE_GOODS, pBarcode));
        //mLogger.i("current state:" + getState());
        mLogger.i("startDownloadGoods:" + pBarcode + " from:" + String.valueOf(pFrom));
        if (getState() == State.NEW) {
            start();
        }
    }

    @Override
    public void run() {
        super.run();
        isProcess = true;
        HTTP_HOST = Configure.getConfigData(Configure.CONFIG_DOWNLOAD_GOODS_DATABASE_URL);
        while (isProcess) {
            SystemClock.sleep(1000);
            if (getTaskQueueCount() > 0) {
                DownloadTaskModel model = getTaskQueueData();
                mType = model.type;
                mBarcode = model.barcode;
                if (mType.equals(TYPE_GOODS)) {
                    isIdle = true;
                } else {
                    isIdle = false;
                }
                startTask();
            } else {
                isIdle = true;
            }
        }
        isProcess = false;
    }

    private void startTask() {
        DownloadGoodsDatabaseUtils.sendOnDownloadOnStartListener();
        mLogger.i("start download:" + mType);
        mGoodsDownloadList.clear();
        //计算sign数据
        String time = Tools.getCurrentTime();
        String avm = Configure.getMacNo();
        StringBuffer signString = new StringBuffer();
        signString.append("api_type=").append("2").append("&");
        signString.append("appid=").append(APPID).append("&");
        signString.append("avm=").append(avm).append("&");
        if (mType.equals(TYPE_GOODS)) {
            signString.append("barcode=").append(mBarcode).append("&");
        }
        signString.append("key=").append(KEY).append("&");
        signString.append("task_type=").append(mType).append("&");
        signString.append("time=").append(time);
        String sign = MD5.md5Encode(signString.toString());
        //拼接post数据
        StringBuffer postData = new StringBuffer();
        postData.append("api_type=").append("2").append("&");
        postData.append("appid=").append(APPID).append("&");
        postData.append("avm=").append(avm).append("&");
        if (mType.equals(TYPE_GOODS)) {
            postData.append("barcode=").append(mBarcode).append("&");
        }
        postData.append("sign=").append(sign).append("&");
        postData.append("task_type=").append(mType).append("&");
        postData.append("time=").append(time);
        mLogger.i("send post:" + postData.toString());
        //请求post数据
        //请求数据时间
        String response = postRequest(HTTP_HOST + INTERFACE_FIND_BARCODE, postData.toString());
        mLogger.i("start response1:" + response);
        if (response == null || "".equals(response)) {
            cleanUp();
            return;
        }
        if (mType.equals(TYPE_ALL)) {
            //删除商品库
            mLogger.i("删除商品库=========================");
            ArrayList<GoodsModel> goodsDataBaseList = GoodsConfiguration.getGoodsDataBaseList();
            if (goodsDataBaseList != null) {
                goodsDataBaseList.clear();
            }
            mLogger.i("goodsDataBaseList1 size:" + goodsDataBaseList.size() + ",goodsDatabaseList:" + goodsDataBaseList.toString());
            GoodsConfiguration.updateGoodsDatabaseXML(goodsDataBaseList);
        }
        //处理JSON
        try {
            response = new String(response.getBytes(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        mLogger.i("response:" + response);
        JSONObject object;
        try {
            object = new JSONObject(response);
            int flag = object.getInt("flag");
            if (flag == 1) {
                cleanUp();
                return;
            }
            int total = object.getInt("total");
            if (total <= 0) {
                cleanUp();
                return;
            }
            mTaskId = object.getString("task_id");
            if (mTaskId == null || "".equals(mTaskId)) {
                cleanUp();
                return;
            }
            JSONArray rows = object.getJSONArray("rows");
            if (rows == null || rows.length() == 0) {
                cleanUp();
                return;
            }
            for (int j = 0; j < total; j++) {

                JSONObject obj = rows.getJSONObject(j);
                GoodsDownloadModel model = GoodsDownloadModel.fromJson(obj);
                mGoodsDownloadList.add(model);

            }
            mLogger.i("mGoodsDownloadList size:" + mGoodsDownloadList.size());
        } catch (JSONException e) {
            mLogger.e("json error:" + e.toString());
            retyrMethod();
            cleanUp();
            return;
        }
        //下载完成后更新goods.xml文件
        contrastXML(mGoodsDownloadList);
        mLogger.i("mGoodsDownloadList2 size:" + mGoodsDownloadList.size());
        //处理每条数据
        if(mType.equals(TYPE_ALL)){
            deleteGoodsDataBaseXML();
        }

        for (GoodsDownloadModel model : mGoodsDownloadList) {
            handleGoodsDownload(model);
            deleteFolder(Configure.path + "/download");
        }
        //拼接body串
        StringBuffer body = new StringBuffer();
        for (GoodsDownloadModel model : mGoodsDownloadList) {
            if (model.failID < 0) {
                continue;
            }
            if (body.length() > 0) {
                body.append(",");
            }
            body.append("{\"barcode\":\"" + model.barcode + "\",\"failID\":\"" + String.valueOf(model.failID) + "\"}");
        }
        body.insert(0, "body=[");
        body.append("]");
        //计算sign数据
        time = Tools.getCurrentTime();
        signString = new StringBuffer();
        signString.append("appid=").append(APPID).append("&");
        signString.append("avm=").append(avm).append("&");
        signString.append(body).append("&");
        signString.append("key=").append(KEY).append("&");
        signString.append("task_id=").append(mTaskId).append("&");
        signString.append("time=").append(time);
        sign = MD5.md5Encode(signString.toString());
        //拼接post数据
        postData = new StringBuffer();
        postData.append("appid=").append(APPID).append("&");
        postData.append("avm=").append(avm).append("&");
        postData.append(body).append("&");
        postData.append("sign=").append(sign).append("&");
        postData.append("task_id=").append(mTaskId).append("&");
        postData.append("time=").append(time);
        mLogger.i("send post:" + postData.toString());
        //请求post数据
        response = postRequest(HTTP_HOST + INTERFACE_FIND_BARCODE_RE, postData.toString());
        mLogger.i("start response3:" + response);
        if (response == null || "".equals(response)) {
            cleanUp();
            return;
        }
        //处理JSON
        mLogger.i("response:" + response);
        cleanUp();
    }

    private void deleteGoodsDataBaseXML() {
        File fileXmlTemp = new File(Configure.path + "/" + DIRECTORY_CONFIG + "/" + GoodsConfiguration.FILE_GOODS_DATABASE + "temp");
        File fileXMLBase = new File(Configure.path + "/" + DIRECTORY_CONFIG + "/" + GoodsConfiguration.FILE_GOODS_DATABASE);
        mLogger.i("fileXmlTemp path:" + (Configure.path + "/" + DIRECTORY_CONFIG + "/" + GoodsConfiguration.FILE_GOODS_DATABASE + "temp"));
        mLogger.i("fileXMLBase path:" + (Configure.path + "/" + DIRECTORY_CONFIG + "/" + GoodsConfiguration.FILE_GOODS_DATABASE));
        if (fileXmlTemp.exists()) {
            fileXmlTemp.delete();
            mLogger.i("删除了" + fileXmlTemp + "文件");
        }
        if (fileXMLBase.exists()) {
            fileXMLBase.delete();
            mLogger.i("删除了" + fileXMLBase + "文件");
        }
        ArrayList<GoodsModel> goodsDataBaseList = GoodsConfiguration.getGoodsDataBaseList();
        if(goodsDataBaseList!=null){
            goodsDataBaseList.clear();
        }

    }

    private void cleanUp() {
        DownloadGoodsDatabaseUtils.sendOnDownOnEndListener();
    }

    private String postRequest(final String pUrl, final String pDataPost) {
        String message = "";
        URL realurl = null;
        InputStream in = null;
        HttpURLConnection conn = null;
        StringBuffer sBuffer = null;
        try {
            realurl = new URL(pUrl);
            conn = (HttpURLConnection) realurl.openConnection();
            conn.setDoInput(true);
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", mContentType + ";charset=" + mCharset);
            conn.setRequestProperty("Accept", "application/json;charset=" + mCharset);
            //post data
            BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());
            byte[] bytes = pDataPost.getBytes(mCharset);
            out.write(bytes, 0, bytes.length);
            out.flush();
            out.close();
            mLogger.i("postRequest getResponseCode:" + conn.getResponseCode());
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {

                sBuffer = new StringBuffer();
                byte[] buf = new byte[1024];
                in = conn.getInputStream();
                for (int n; (n = in.read(buf)) != -1; ) {
                    sBuffer.append(new String(buf, 0, n, "UTF-8"));
                }
                message = sBuffer.toString();
                mLogger.i("postRequest message:" + message);
            } else {
                mLogger.e("http error, response code:" + conn.getResponseCode());
                retyrMethod();
            }

        } catch (MalformedURLException e) {
            mLogger.e("MalformedURLException--" + e.toString());
            retyrMethod();
        } catch (ProtocolException e) {
            mLogger.e("ProtocolException--" + e.toString());
            retyrMethod();
        } catch (UnsupportedEncodingException e) {
            mLogger.e("UnsupportedEncodingException--" + e.toString());
            retyrMethod();
        } catch (SocketTimeoutException e) {
            mLogger.e("SocketTimeoutException--" + e.toString());
            retyrMethod();
        } catch (UnknownHostException e) {
            mLogger.e("UnknownHostException--" + e.toString());
            retyrMethod();
        } catch (IOException e) {
            mLogger.e("IOException--" + e.toString());
            retyrMethod();
        } finally {
            try {
                if (in != null) in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (conn != null) conn.disconnect();
        }
        return message;
    }

    private void handleGoodsDownload(final GoodsDownloadModel pModel) {
        if (pModel == null) {
            return;
        }
        if (mType.equals(TYPE_ALL) || mType.equals(TYPE_PART)) {
            handleTypeALL(pModel);
        } else if (mType.equals(TYPE_GOODS)) {
            handleTypeGoods(pModel);
        }
    }

    private void handleTypeALL(final GoodsDownloadModel pModel) {
        ArrayList<GoodsModel> goodsDataBaseList = GoodsConfiguration.getGoodsDataBaseList();
        mLogger.i("handleTypeAll goodsDataBaseList size:" + goodsDataBaseList.size() + ",goodsDatabaseList:" + goodsDataBaseList.toString());

        if(mType.equals(TYPE_ALL)){
            if(goodsDataBaseList.size()!=0&&isFirstLoopDeleteAllGoods){
                goodsDataBaseList.clear();
                isFirstLoopDeleteAllGoods=false;
            }
        }

        if (goodsDataBaseList == null) {
            mLogger.e("update xml fail:" + pModel.barcode);
            pModel.failID = FAIL_ID_XML;
            return;
        }
        GoodsModel goods = new GoodsModel();
        try {
            goods.setName(URLDecoder.decode(pModel.nameURLEncoder, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            goods.setName(pModel.name);
        }
        if (goods.getName() == null || "".equals(goods.getName())) {
            if (pModel.name == null || "".equals(pModel.name)) {
                goods.setName("");
            } else {
                goods.setName(pModel.name);
//                goods.setName(pModel.name);
            }
        }
        goods.setBarCode(pModel.barcode);
        goods.setKind(pModel.kind);
        //更新到总库中
        boolean isHave = false;
//        mLogger.i("loop goodsDataBaseList size:"+goodsDataBaseList.size());
        for (GoodsModel model : goodsDataBaseList) {
            if (model.getBarCode().equals(goods.getBarCode())) {
                isHave = true;
                model.setName(goods.getName());
                model.setKind(goods.getKind());
                break;
            }
        }
        if (!isHave) {
            goodsDataBaseList.add(goods);
        }
//        Configure.goodsDataBaseList.add(goods);
//        //去重
//        Configure.goodsDataBaseList = new ArrayList<>(new HashSet<>(Configure.goodsDataBaseList));

//        mLogger.i("goodsDataBaseList2 size:" + goodsDataBaseList.size() + ",goodsDatabaseList:" + goodsDataBaseList.toString());
        GoodsConfiguration.updateGoodsDatabaseXML(goodsDataBaseList);
    }

    private void handleTypeGoods(final GoodsDownloadModel pModel) {
        if (pModel.prodataUrl == null || "".equals(pModel.prodataUrl)) {
            pModel.failID = FAIL_ID_DOWNLOAD;
            return;
        }

        File downloadDir = new File(Configure.path + "/download");
        if (!downloadDir.exists()) {
            downloadDir.mkdirs();
        }

        String srcDir = downloadDir.getAbsolutePath();
        String disDir = Configure.path + "/images/goods_image/";

        if (checkFileMD5(new File(disDir + pModel.barcode), pModel.prodataMd5)) //检查是否MD5值一样，一样就无需下载
        {
            return;
        }
        String downloadFile = downloadDir.getAbsolutePath() + "/download.zip";
        boolean isSuccess = downloadFileByHTTP(pModel.prodataUrl, downloadFile);
        if (!isSuccess) {
            pModel.failID = FAIL_ID_DOWNLOAD;
            return;
        }
        //解压缩文件
        boolean unzip;
        try {
            // 解压文件
            unzip = unZipFolder(downloadFile, downloadDir.getAbsolutePath());
        } catch (FileNotFoundException e) {
            mLogger.i("unzip FileNotFoundException:" + e.getMessage());
            pModel.failID = FAIL_ID_UNZIP;
            return;
        } catch (IOException e) {
            mLogger.i("unzip IOException:" + e.getMessage());
            pModel.failID = FAIL_ID_UNZIP;
            return;
        }
        if (!unzip) {
            pModel.failID = FAIL_ID_UNZIP;
            return;
        }
        //删除zip文件
        File zipFile = new File(downloadFile);
        String md5 = "";
        try {
            md5 = MD5.getFileMD5String(zipFile);
        } catch (IOException e) {

        }
        zipFile.delete();

        //检查下是否有商品国标码目录
        File bcDir = new File(srcDir + "/" + pModel.barcode);
        if (!bcDir.exists()) {
            disDir += pModel.barcode;
            File disDirFile = new File(disDir);
            if (!disDirFile.exists()) {
                if (!disDirFile.mkdirs()) {
                    mLogger.e("mkdir fail:" + pModel.barcode);
                    pModel.failID = FAIL_ID_COPY;
                    return;
                }
            }
        }

        //拷贝文件
        int copyResult = copy(srcDir, disDir);
        if (copyResult != 0) {
            mLogger.e("copy fail:" + pModel.barcode);
            pModel.failID = FAIL_ID_COPY;
            return;
        }

//        File pngFile = new File(Configure.path + "/images/goods_image/" + pModel.barcode + "/0.png");
//        try {
//            mLogger.i("0.png MD5:" + MD5.getFileMD5String(pngFile));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        //写入MD5值到文件中
        if (!md5.equals("")) {
            File md5file = new File(Configure.path + "/images/goods_image/" + pModel.barcode + "/md5.txt");
            mLogger.i("file:" + md5file.getAbsolutePath() + " md5:" + md5);
            boolean result = FileTools.writeFile(md5file, md5);
            if (!result) {
                mLogger.e("write md5 fail:" + pModel.barcode);
                pModel.failID = FAIL_ID_COPY;
            }
        }
    }

    private boolean checkFileMD5(File pBcDir, final String pMd5) {
        if (pMd5 == null || pMd5.equals("")) {
            return false;
        }
        File md5file = new File(pBcDir.getAbsolutePath() + "/md5.txt");
        if (!md5file.exists()) {
            return false;
        }
        String md5 = FileTools.readFile(md5file);
        if (md5 == null || md5.equals("")) {
            return false;
        }
        mLogger.i("file md5:" + md5 + " server md5:" + pMd5);
        if (md5.toUpperCase().equals(pMd5.toUpperCase())) {
            return true;
        }
        return false;
    }

    private boolean downloadFileByHTTP(final String pUrl, final String pFile) {
        mLogger.i("downloading file:" + pUrl);
        boolean result = false;
        File downloadFile = new File(pFile);
        int bytesum = 0;
        int byteread;
        URLConnection conn = null;
        InputStream inStream = null;
        FileOutputStream fs = null;
        try {
            URL url = new URL(pUrl);
            conn = url.openConnection();
            inStream = conn.getInputStream();
            fs = new FileOutputStream(downloadFile);

            byte[] buffer = new byte[1024];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                System.out.println(bytesum);
                fs.write(buffer, 0, byteread);
                fs.flush();
            }
            result = true;
        } catch (MalformedURLException e) {
            mLogger.e(e.toString());
        } catch (FileNotFoundException e) {
            mLogger.e(e.toString());
        } catch (IOException e) {
            mLogger.e(e.toString());
        } finally {
            try {
                if (inStream != null) inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fs != null) fs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    private boolean unZipFolder(String zipFileString, String outPathString) throws IOException {
        File zipFile = new File(zipFileString);
        if (!zipFile.exists()) {
            mLogger.i("unzip failed file no exists " + zipFileString);
            return false;
        }

        File desDir = new File(outPathString);
        if (!desDir.exists())
            desDir.mkdirs();

        BufferedInputStream bi;
        ZipFile zf = new ZipFile(zipFile);
        Enumeration<?> e = zf.entries();
        while (e.hasMoreElements()) {
            ZipEntry ze2 = (ZipEntry) e.nextElement();
            String entryName = ze2.getName();
            String path = outPathString + "/" + entryName;

            mLogger.i("entryName = " + entryName);

            if (ze2.isDirectory()) {
                // mLogger.i("正在创建解压目录 - " + entryName);
                File decompressDirFile = new File(path);
                if (!decompressDirFile.exists()) {
                    decompressDirFile.mkdirs();
                }
            } else {
                String fileDir = path.substring(0, path.lastIndexOf("/"));
                File fileDirFile = new File(fileDir);
                if (!fileDirFile.exists()) {
                    fileDirFile.mkdirs();
                }
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path));
                bi = new BufferedInputStream(zf.getInputStream(ze2));
                byte[] readContent = new byte[1024];
                int readCount = bi.read(readContent);
                while (readCount != -1) {
                    bos.write(readContent, 0, readCount);
                    readCount = bi.read(readContent);
                }
                bos.close();
            }
        }
        zf.close();
        mLogger.i("unzip success! " + zipFileString);
        return true;
    }

    /**
     * 拷贝文件夹下所有的东西
     *
     * @param fromFile
     * @param toFile
     * @return 0 代表成功 -1 代表失败
     */
    public static int copy(String fromFile, String toFile) {
        // 要复制的文件目录
        File[] currentFiles;
        File root = new File(fromFile);
        // 如同判断SD卡是否存在或者文件是否存在
        // 如果不存在则 return出去
        if (!root.exists()) {
            return -1;
        }
        // 如果存在则获取当前目录下的全部文件 填充数组
        currentFiles = root.listFiles();

        // 目标目录
        File targetDir = new File(toFile);
        // 创建目录
        if (!targetDir.exists()) {
            //mLogger.i("dir does not exist");
            targetDir.mkdirs();
            //mLogger.i("make dir result : " + targetDir.exists());
        }
        // 遍历要复制该目录下的全部文件
        //mLogger.i("file count = " + currentFiles.length);
        for (int i = 0; i < currentFiles.length; i++) {
            if (currentFiles[i].isDirectory())// 如果当前项为子目录 进行递归
            {
//				mLogger.i("\r\n");
//				mLogger.i("文件夹 ：name = " + currentFiles[i].getName()
//						+ "\r\n fromPath = " + currentFiles[i].getPath()
//						+ "/\r\n destPath = " + toFile + "/"
//						+ currentFiles[i].getName() + "/");
                copy(currentFiles[i].getPath() + "/", toFile + "/"
                        + currentFiles[i].getName());

            } else// 如果当前项为文件则进行文件拷贝
            {
//				mLogger.i("文件：name = " + currentFiles[i].getName()
//						+ "\r\n fromPath = " + currentFiles[i].getPath()
//						+ "\r\n destPath = " + toFile + "/"
//						+ currentFiles[i].getName());
                copyFile(currentFiles[i].getPath(), toFile + "/"
                        + currentFiles[i].getName());
            }
        }
        return 0;
    }

    /**
     * 拷贝文件
     *
     * @param fromFile
     * @param toFile
     * @return 0 代表成功 -1 代表失败 -- 抛异常
     */
    public static int copyFile(String fromFile, String toFile) {

        InputStream in = null;
        BufferedReader reader = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(fromFile);
            // reader = new BufferedReader(new InputStreamReader(in));
            out = new FileOutputStream(toFile);
            // BufferedWriter writer = new BufferedWriter(new
            // OutputStreamWriter(out));
            // String line = "";
            int len = -1;
            byte[] buffer = new byte[1024 * 4];
            long start = System.currentTimeMillis();
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
                // out.write(line.getBytes());
                // writer.write(line);
            }
            long end = System.currentTimeMillis();
//			mLogger.i("cast time : " + (end - start) + "s");
            return 0;

        } catch (Exception ex) {
            return -1;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 删除指定目录下的全部文件和目录，目录本身不删除
     *
     * @param pCleanFolder 要清理的目录
     */
    public static void deleteFolder(final String pCleanFolder) {
        File folder = new File(pCleanFolder);
        if (!folder.exists())
            return;
        if (folder.isFile()) {
            folder.delete();
            return;
        }
        File[] files = folder.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                String name = file.getName();
                if (!".".equals(name) && !"..".equals(name)) {
                    deleteFolder(file.getAbsolutePath());
                }
                file.delete();
            }
        }
    }

    class DownloadTaskModel {
        String type;
        String barcode;

        public DownloadTaskModel(final String pType, final String pBarcode) {
            type = pType;
            barcode = pBarcode;
        }

        @Override
        public String toString() {
            return "type:" + type + ",barcode:" + barcode;
        }
    }

    /**
     * 更新goods.xml
     *
     * @param mGoodsDownloadList
     */
    private void contrastXML(ArrayList<GoodsDownloadModel> mGoodsDownloadList) {
        ArrayList<GoodsModel> goodsList = GoodsConfiguration.getGoodsList();
        for (GoodsModel goodsModel : goodsList) {
            for (GoodsDownloadModel goodsDownloadModel : mGoodsDownloadList) {
                if (goodsModel.getBarCode().equals(goodsDownloadModel.barcode)) {
                    try {
                        String name = URLDecoder.decode(goodsDownloadModel.nameURLEncoder, "UTF-8");
                        if (!goodsModel.getName().equals(/*goodsDownloadModel.name*/name)) {
//                        mLogger.i("contrastXML goodsDownloadModel name:"+goodsDownloadModel.name);
//                        goodsModel.setName(goodsDownloadModel.name);

                            goodsModel.setName(name);

                        }
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }
        GoodsConfiguration.updateGoodsXML(goodsList);
    }


    private void retyrMethod() {
        if (retryCount < 3) {
            SystemClock.sleep(3000);
            retryCount++;
            mLogger.i("retry: " + retryCount);
            DownloadGoodsDatabaseThread.getInstance().startDownload(mType);
        } else {
            retryCount = 0;
        }
    }


}
